<template>
    <view>
        <view class="control_panel_upper">
            <view class="connection_info_div">{{ currentDevName }}({{ currentConnectionState }})</view>
			<view></view>
			<view>id:{{ yundan.ydbh }}</view>
        </view>
        
    <view class="printPart">
        <scroll-view :scroll-y="true" style="height: 100%" :scroll-top="scrollTop">
            <!-- 将输入框和按钮放在同一行 -->
            <view class="input-row">
                <input type="number" v-model="startNumber" placeholder="输入起始序号" class="input-field" />
                <input type="number" v-model="endNumber" placeholder="输入结束序号" class="input-field" />

                <!-- 打印按钮放在同一行 -->
                <view class="print-btn2" @tap="bfprintBtn" :data-index="cpclIndex">部分打印</view>
            </view>
        </scroll-view>
    </view>
        
        <!-- Display printnrall list -->
		<view class="printnrall_list">
            <scroll-view :scroll-y="true" style="height: 100%">
                <view v-for="(item, index) in printnrallshow" :key="index" class="print_item">
					<view>序号: {{ index+1 }}<button class="print-btn3"  @tap="printSingle(index)">单个打印</button></view>
                    <view>单号: {{ item.fbcode }}</view>
                    <view>裁床号: {{ item.mid }}</view>
                    <view>时间: {{ item.time }}</view>
                    <view>款号: {{ item.kh }} ,颜色: {{ item.ys }} ,尺码: {{ item.cm }}</view>
                    <view>数量: {{ item.sl }} ,价格: {{ item.jg }}</view>
                    <view>备注: {{ item.bz }}</view>
                    
					<!-- <view class="print-btn3" @tap="printBtn" :data-index="cpclIndex">单个打印</view> -->
                </view>
            </scroll-view>
		</view>

        <view class="RecvStatus1">
			<view class="print-btn" @tap="printall(1)">全部打印</view>
        </view>
		<view class="RecvStatus">
		    <view class="recv_total_bytes">接收:{{ recvTotalBytes }}字节</view>
			
		    <button class="clear_button" @tap="bindButtonClearAll">清除</button>
		</view>

        <view class="container_recv">
            <scroll-view :scroll-y="true" style="height: 100%" :scroll-top="scrollTop">
                <view style="height: 200px">
                    {{ recv_data }}
                </view>
            </scroll-view>
        </view>
    </view>
</template>


<script>
var app = getApp();
let gbToBase64 = require('../../utils/gb2312ToBase64.js');
const cpcl = require('../../utils/cpcl.js');
const tspl = require('../../utils/tspl.js');
const esc = require('../../utils/esc.js');
export default {
    data() {
        return {
            startNumber: '', // 绑定到第一个输入框
            endNumber: '', // 绑定到第二个输入框			
			printnrallshow: [], // 定义 printnrallshow
			yundan:[],
			printnr:'',
			printnrcs:'',
			ydid: 0,
            cpcl: 'CPCL-三寸便携(QR386)',
            tspl: 'TSPL-四寸桌面(QR488/588)',
            esc: 'ESC-两寸便携',
            cpclIndex: '0',
            tsplIndex: '1',
            escIndex: '2',
            currentDevName: 'defaulName',
            currentConnectionState: '已连接',
            recvTotalBytes: '0',
            recv_data: '',
            scrollTop: 0,
            send_data: '',
            devId: '123',
            services: ['22'],
            connected: false,
            notifyServiceId: 'invalid',
            notifyCharacteristicId: 'invalid',
            notifyServiceSearchIndex: 0,
            writeServiceId: 'invalid',
            writeCharacteristicId: 'invalid',
            writeServiceSearchIndex: 0
        };
    },
    onLoad: function (options) {
        var btDevId = options.devId;
		var ydidop = options.ydid;
        var that = this;
		that.ydid=ydidop;
		console.log('运单id', ydidop);
        var num = that.services.length;
        that.services.splice(0, num);
        that.setData({
            services: that.services,
			ydid: ydidop
        });
        for (var i = 0; i < app.globalData.btDevices.length; ++i) {
            if (app.globalData.btDevices[i].devId == btDevId) {
                console.log('!!!createBLEConnection', btDevId);
                that.setData({
                    currentDevName: app.globalData.btDevices[i].name,
                    currentConnectionState: '连接中...'
                });
                uni.createBLEConnection({
                    // 这里的 btDevId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                    deviceId: app.globalData.btDevices[i].devId,
                    success: function (res) {
                        console.log(res);
                        that.devId = btDevId;
                        uni.getBLEDeviceServices({
                            // 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                            deviceId: that.devId,
                            success: function (res) {
                                console.log('device services:', res.services);
                                // 保存已连接设备的服务
                                for (var j = 0; j < res.services.length; ++j) {
                                    var newService = [res.services[j]];
                                    that.services = that.services.concat(newService);
                                    console.log(j, that.services.length, res.services.length);
                                }
                                that.setData({
                                    services: that.services
                                });

                                // 寻找第一个Notify特征
                                that.notifyServiceSearchIndex = 0;
                                that.notifyCharacteristicId = 'invalid';
                                that.seekFirstNotifyCharacteristic();
                            }
                        });
                    }
                });
                break;
            }
        }
		that.chaxun();
		
    },
    onShow: function () {
        var that = this;
        uni.onBLECharacteristicValueChange(function (res) {
            var lang = that.recv_data;
            if (String.fromCharCode.apply(null, new Uint8Array(res.value)) == 'OK') {
                uni.showToast({
                    title: '打印成功',
                    icon: 'success',
                    duration: 2000
                });
            }
            console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`);
            console.log(String.fromCharCode.apply(null, new Uint8Array(res.value)));
            lang += String.fromCharCode.apply(null, new Uint8Array(res.value));
            that.setData({
                recvTotalBytes: lang.length.toString(),
                recv_data: lang
                // scrollTop: that.data.scrollTop + 20
            });
        });

        uni.onBLEConnectionStateChanged(function (res) {
            console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`);
        });
        uni.onBluetoothAdapterStateChange(function (res) {
            console.log(`adapterState changed, now is`, res);
        });
    },
    onUnload: function () {
        var that = this;
        uni.closeBLEConnection({
            deviceId: that.devId,
            success: function (res) {
                console.log(res);
            }
        });
    },
    methods: {
		chaxun(){
			var that=this;
			console.log(that.ydid);
			wx.request({
			url:getApp().globalData.host+'api.php?',//请求地址
			data:{//发送给后台的数据
		    m:"openwx",
		    a:"yundan",
		    dh:that.ydid,
			// dh:15,
				},
			header:{
			//请求头
		    // "Content-Type":"applciation/json",
			"Content-Type":"text/html; charset=UTF-8",
				},
			method:"GET",//get为默认方法/POST
			success:function(res){
				console.log("运单结果");
				console.log(res.data);//res.data相当于ajax里面的data,为后台返回的数据	
				that.yundan=res.data;
				that.printnr=res.data.nr;
				that.printnrcs=res.data.csnr;
				console.log("打印结果");
				console.log(that.printnr);
				//拼接开始
				// 假设res.data.nr和res.data.csnr已经存在
				let nrArray = res.data.nr; // 获取数组
				let csnrTemplate = res.data.csnr; // 获取模板
				
				let printnrall = []; // 用于存放最终结果
				let printnrallshow = []; // 用于存放最终结果
				    const now = new Date();
				    // const nowtime= now.toLocaleString(); 
					const nowtime = now.toLocaleString('zh-CN', { 
					    year: 'numeric', 
					    month: '2-digit', 
					    day: '2-digit', 
					    hour: '2-digit', 
					    minute: '2-digit', 
					    second: '2-digit',
					    hour12: false
					}).replace(/\//g, '-'); // 可以根据需求调整格式
					console.log(nowtime);
				// 遍历nr数组
				let xh=1;
				nrArray.forEach(item => {
				    // 假设你要用到的字段包括id, mid, dh等，可以根据需求进行调整
				    let filledTemplate = csnrTemplate
				        .replace(/{{fbcode}}/g, item.fbcode)
				        .replace(/{{mid}}/g, item.dh+'-'+xh)
				        .replace(/{{time}}/g, nowtime)
				        .replace(/{{kh}}/g, item.kh)
				        .replace(/{{ys}}/g, item.ys)
				        .replace(/{{cm}}/g, item.cm)
				        .replace(/{{sl}}/g, item.sl)
				        .replace(/{{jg}}/g, item.jg ? item.jg : ' ')
				        .replace(/{{bz}}/g, item.bz);
				
				    // 将填充后的模板推入printnrall数组
				       printnrall.push(filledTemplate);
					   let filledTemplateshow = {
					           fbcode: item.fbcode,
					           mid: item.dh+'-'+xh,
					           time: nowtime,
					           kh: item.kh,
					           ys: item.ys,
					           cm: item.cm,
					           sl: item.sl,
					           jg: item.jg ? item.jg : ' ',
					           bz: item.bz
					       };
					       printnrallshow.push(filledTemplateshow);
						   xh=xh+1;
				});
				
				// 将最终结果赋值给that.printnrall
				that.printnrall = printnrall;
				that.printnrallshow = printnrallshow;
				
				// 可以在此打印输出结果进行验证
				console.log("填充后的打印内容:");
				console.log(that.printnrall);
				console.log("填充后的列表内容:");
				console.log(that.printnrallshow);
				
				//拼接结束

				// dh:  that.dh,
				// kh: res.data.kh,
				// ys: res.data.ys,
				// cm:  res.data.cm,
				// sl:  res.data.sl,
				// nr: res.data.zyqztwenben,
				// zsl: res.data.zsl,
				// slwf: res.data.slwf,
			},
		  fail:function(err){
			  console.log("入库失败");
					 
					 		 
				  },//请求失败
		  complete:function(){}//请求完成后执行的函数
		})
		//结束提交	
		},		
        seekFirstNotifyCharacteristic: function () {
            var that = this;
            if (that.notifyServiceSearchIndex < that.services.length && that.notifyCharacteristicId == 'invalid') {
                that.notifyServiceId = that.services[that.notifyServiceSearchIndex].uuid;
                console.log('Search service index ', that.notifyServiceSearchIndex, 'service: ', that.notifyServiceId);
                ++that.notifyServiceSearchIndex;
                uni.getBLEDeviceCharacteristics({
                    // 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                    deviceId: that.devId,
                    // 这里的 notifyServiceId 需要在 getBLEDeviceServices 接口中获取
                    serviceId: that.notifyServiceId,
                    complete: function () {
                        console.log('device getBLEDeviceCharacteristics complete', that.notifyServiceSearchIndex);
                        //递归调用自身直到找到notify特征或遍历完所有特征
                        that.seekFirstNotifyCharacteristic();
                    },
                    success: function (res) {
                        console.log('device getBLEDeviceCharacteristics:', res.characteristics);
                        for (var n = 0; n < res.characteristics.length && that.notifyCharacteristicId == 'invalid'; ++n) {
                            if (res.characteristics[n].properties.notify == true) {
                                console.log('device notify Characteristics found', n);
                                that.notifyCharacteristicId = res.characteristics[n].uuid;
                                console.log('notify servcie:', that.notifyServiceId);
                                console.log('notify characteristic:', that.notifyCharacteristicId);
                                console.log('start notify');
                                uni.notifyBLECharacteristicValueChanged({
                                    state: true,
                                    // 启用 notify 功能
                                    // 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                                    deviceId: that.devId,
                                    // 这里的 notifyServiceId 需要在 getBLEDeviceServices 接口中获取
                                    serviceId: that.notifyServiceId,
                                    // 这里的 notifyCharacteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
                                    characteristicId: that.notifyCharacteristicId,
                                    success: function (res) {
                                        console.log('notifyBLECharacteristicValueChanged success', res.errMsg);
                                        uni.showToast({
                                            title: '连接成功',
                                            icon: 'success',
                                            duration: 2000
                                        });
                                        that.setData({
                                            currentConnectionState: '已连接',
                                            connected: true
                                        });

                                        // 寻找第一个write特征
                                        that.writeServiceSearchIndex = 0;
                                        that.writeCharacteristicId = 'invalid';
                                        that.seekFirstWriteCharacteristic();
                                    }
                                });
                            }
                        }
                    }
                });
            }
        },

        seekFirstWriteCharacteristic: function () {
            var that = this;
            if (that.writeServiceSearchIndex < that.services.length && that.writeCharacteristicId == 'invalid') {
                that.writeServiceId = that.services[that.writeServiceSearchIndex].uuid;
                console.log('Search service index ', that.writeServiceSearchIndex, 'service: ', that.writeServiceId);
                ++that.writeServiceSearchIndex;
                uni.getBLEDeviceCharacteristics({
                    // 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                    deviceId: that.devId,
                    // 这里的 writeServiceId 需要在 getBLEDeviceServices 接口中获取
                    serviceId: that.writeServiceId,
                    complete: function () {
                        console.log('device getBLEDeviceCharacteristics complete', that.writeServiceSearchIndex);
                        //递归调用自身直到找到write特征或遍历完所有特征
                        that.seekFirstWriteCharacteristic();
                    },
                    success: function (res) {
                        console.log('device getBLEDeviceCharacteristics:', res.characteristics);
                        for (var n = 0; n < res.characteristics.length && that.writeCharacteristicId == 'invalid'; ++n) {
                            if (res.characteristics[n].properties.write == true) {
                                console.log('device write Characteristics found', n);
                                that.writeCharacteristicId = res.characteristics[n].uuid;
                                console.log('write servcie:', that.writeServiceId);
                                console.log('write characteristic:', that.writeCharacteristicId);
                            }
                        }
                    }
                });
            }
        },

        bindButtonClearAll: function (e) {
            var that = this;
            console.log('clearAll');
            that.setData({
                recv_data: '',
                recvTotalBytes: '0'
            });
        },
		//单个打印
		printSingle: function (index) {

			    this.printBatch(index, null, null); // 将范围转换为索引
	
		},	
		//部分打印
		bfprintBtn() {
		        if (this.startNumber && this.endNumber) {
		            this.printBatch(null, this.startNumber - 1, this.endNumber - 1); // 将范围转换为索引
		        } else {
		            uni.showToast({
		                title: '请填写起始和结束序号',
		                icon: 'none',
		                duration: 2000
		            });
		        }
		    },
			//全部打印
			printall: function (index) {
			
				    this.printBatch(null, null, null); // 将范围转换为索引
				
			},
		// 打印模块功能
		printBatch: function (id = null, startIndex = null, endIndex = null) {
			console.log("id");
			console.log(id);
			console.log("startIndex");
			console.log(startIndex);
			console.log("endIndex");
			console.log(endIndex);
		    var that = this;					
		    if (that.connected) {
		        const printDocument = (document, index) => {
		            return new Promise((resolve) => {
		                //console.log("打印内容");
		                //console.log(document); // 打印当前文档内容
		
		                const sendData = document.replace(/\\r\\n/g, '\r\n'); // 替换换行符
		                console.log("打印sendData内容");
		                console.log(sendData);
		
		                // 2秒延迟
		                setTimeout(() => {
		                    const base64Str = gbToBase64.encode64(sendData);
		                    const arrayBuffer = uni.base64ToArrayBuffer(base64Str);
		
		                    uni.writeBLECharacteristicValue({
		                        deviceId: this.devId,
		                        serviceId: this.writeServiceId,
		                        characteristicId: this.writeCharacteristicId,
		                        value: arrayBuffer,
		                        success: function (res) {
		                            console.log('发送成功', res.errMsg);
		                        },
		                        fail: function (res) {
		                            console.log('发送失败', res.errMsg);
		                        }
		                    });
		
		                    resolve(); // 处理完成
		                }, 2000); // 延迟2秒
		            });
		        };
		
		        // 使用that.printnrall中的内容
		                let printPromises;
		        
		                if (startIndex !== null && endIndex !== null) {
		                    // 打印范围
		                    printPromises = that.printnrall.map((document, index) => {
		                    return index >= startIndex && index <= endIndex ? printDocument(document, index) : Promise.resolve();
		                    });
		                } else if (id !== null) {
		                    // 打印单条
		                    printPromises = [printDocument(that.printnrall[id], id)];
		                } else {
		                    // 打印全部
		                    printPromises = that.printnrall.map((document, index) => printDocument(document, index));
		                }
		
		        // 等待所有打印完成
		        Promise.all(printPromises).then(() => {
		            uni.showToast({
		                title: '打印完成',
		                icon: 'success',
		                duration: 2000
		            });
		        });
		    } else {
		        uni.showToast({
		            title: '打印机未连接',
		            icon: 'fail',
		            duration: 2000
		        });
		    }
		},
        writeFuction(that, data, count, size) {
            let dataView_temp1 = new DataView(data);
            var packages = Math.round(dataView_temp1.byteLength / size + 0.5);
            var yushu = dataView_temp1.byteLength % size;
            let buffer = null;
            let dataView_temp2 = null;
            if (yushu != 0 && count == 1) {
                buffer = new ArrayBuffer(yushu);
                dataView_temp2 = new DataView(buffer);
                for (var i = 0; i < dataView_temp2.byteLength; i++) {
                    dataView_temp2.setUint8(i, dataView_temp1.getUint8((packages - count) * size + i));
                }
            } else {
                buffer = new ArrayBuffer(size);
                dataView_temp2 = new DataView(buffer);
                for (var i = 0; i < dataView_temp2.byteLength; i++) {
                    dataView_temp2.setUint8(i, dataView_temp1.getUint8((packages - count) * size + i));
                }
            }
            uni.writeBLECharacteristicValue({
                // 这里的 devId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                deviceId: that.devId,
                // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                serviceId: that.writeServiceId,
                // 这里的 writeCharacteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
                characteristicId: that.writeCharacteristicId,
                // 这里的value是ArrayBuffer类型
                value: buffer,
                // value: arrayBuffer,
                success: function (res) {
                    if (count != 0) {
                        that.writeFuction(that, data, count, size);
                    } else {
                        uni.showToast({
                            title: '发送成功',
                            icon: 'success',
                            duration: 2000
                        });
                    }
                },
                complete: function (res) {
                    console.log(res);
                }
            });
            count--;
            return 0;
        }
    }
};
</script>
<style>
page {
    height: 100%;
    overflow: hidden;
}
.input-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 2rpx;
}

.input-field {
    width: 200rpx; /* 控制输入框宽度 */
	 height: 75rpx; /* 增加高度 */
    padding: 2rpx;
    margin-left: 20rpx;
    border: 1px solid #ddd;
    border-radius: 5rpx;
}

.print-btn2 {
    width: 180rpx; /* 控制按钮宽度 */
    height: 75rpx;
    background-color: #0090ff;
    color: #fff;
    font-size: 32rpx;
    border-radius: 10rpx;
    display: flex;
    justify-content: center;
    align-items: center;
}
.print-btn3 {
	position: absolute;
	right: 0; /* 将按钮定位到右侧 */
    width: 180rpx; /* 控制按钮宽度 */
    height: 75rpx;
    background-color: #0090ff;
    color: #fff;
    font-size: 28rpx;
    border-radius: 10rpx;
    display: flex;
    justify-content: center;
    align-items: center;
}

.control_panel_upper {
    position: absolute;
    top: 1%;
    left: 10rpx;
    width: 720rpx;
    height: 7%;
    overflow: hidden;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    font-size: 30rpx;
}

.control_panel_upper .connection_info_div {
    position: absolute;
    top: 10%;
    left: 10rpx;
}

.printPart {
    position: absolute;
    top: 5%;
    left: 10rpx;
    width: 720rpx;
    height: 20%;
    overflow: hidden;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    font-size: 30rpx;
}

.printnrall_list {
    position: absolute;
    top: 12%;
    left: 10rpx;
    width: 720rpx;
    height: 60%;
    overflow: hidden;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background-color: #f9f9f9;
}

.print_item {
    margin-bottom: 15px;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 3px;
    background-color: #fff;
}

.print_item view {
    margin-bottom: 5px;
}

button {
    margin-top: 10px;
    padding: 5px 10px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 3px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}

.RecvStatus1 {
    position: absolute;
    align-items: center;
    bottom: 20%;
    left: 10rpx;
    width: 720rpx;
    height: 8%;
    overflow: hidden;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    font-size: 30rpx;
}
.RecvStatus {
    position: absolute;
    align-items: center;
    bottom: 15%;
    left: 10rpx;
    width: 720rpx;
    height: 5%;
    overflow: hidden;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    font-size: 30rpx;
}

.RecvStatus .clear_button {
    position: absolute;
    right: 0rpx;
    width: 100rpx;
    height: 80%;
    font-size: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
}

.container_recv {
    position: absolute;
    border: 2px solid #000;
    bottom: 3%;
    left: 10rpx;
    width: 720rpx;
    height: 10%;
    overflow: hidden;
    font-size: 30rpx;
}

.print-btn {
    width: 100%;
    height: 75rpx;
    background-color: #0090ff;
    color: #fff;
    font-size: 32rpx;
    border-radius: 25rpx;
    margin-top: 20rpx;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>